package com.zbdx.controller;

import com.zbdx.dao.CarDao;
import com.zbdx.dao.impl.CarDaoImpl;
import com.zbdx.domain.User;
import com.zbdx.domain.product;
import com.zbdx.domain.productVo;
import com.zbdx.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @Author ghp
 * @Creat 2024/9/19 20:13
 * @Version 1.0
 * Description:
 */
@WebServlet("/shopping/car/insertGoods")
public class insertServlet extends HttpServlet {
    private CarDao carDao=new CarDaoImpl();
    private QueryRunner qr=new QueryRunner(DruidUtil.getDataSource());
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name = req.getParameter("name");
        String price = req.getParameter("price");
        productVo productVo = new productVo();
        productVo.setPName(name);
        productVo.setPPrice(price);

        // 获取用户id
        HttpSession session = req.getSession();
        String username = (String) session.getAttribute("user");
        String sql="SELECT * FROM users2 WHERE username=?";
        User user = null;
        try {
            user = qr.query(sql, new BeanHandler<User>(User.class), username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        int userId = user.getId();
        productVo.setUserId(userId);


        sql="select * from product where PName=?";
        try {
            product product = qr.query(sql, new BeanHandler<>(product.class),name);
            productVo.setPNum(product.getPNum());
            productVo.setMId(1);
            productVo.setPImage01(product.getPImage01());
            productVo.setPType(product.getPType());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


        int row = 0;
        try {
            row = carDao.insertProduct(productVo);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.getWriter().print(row);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
